<?php

namespace app\utils\base\helper;

class Ltcms_system_info
{
    /**
     * 获取php版本
     * @param string $dataType
     * @return array|string
     */
    public static function phpVersion()
    {
        $phpVersion=phpversion();
        if($phpVersion==="false"){
            return false;
        }
        $return=array();
        list($major,$minor,$release)=array_pad(explode(".",$phpVersion),3,0);
        $return["data"]=$phpVersion;
        $return["major"]=$major;
        $return["minor"]=$minor;
        $return["release"]=$release;
        return $return;
    }

     /**
     * 获取php版本
     * @param string $dataType
     * @return array|string
     */
    public static function phpVersionId()
    {
        if (!defined('PHP_VERSION_ID')) {
            $version = array_pad(explode('.', PHP_VERSION),3,0);
            $phpVersionId=$version[0] * 10000 + $version[1] * 100 + $version[2];
        }else{
            $phpVersionId=PHP_VERSION_ID;
        }
        $return=array();
        $return["data"]=$phpVersionId;
        $return["major"]=strrev(substr(strrev($phpVersionId),"4",2));
        $return["minor"]=substr($phpVersionId,"-4",2);
        $return["release"]=substr($phpVersionId,"-2",2);
        return $return;
    }

    /**
     * 定义php版本常量
     */
    public static function dfPhpVersionConstant()
    {
        $data=self::phpVersionId();
        if (!defined('PHP_VERSION_ID')) {
            if ($data["data"] < 50207) {
                define('PHP_MAJOR_VERSION',   $data["major"]);
                define('PHP_MINOR_VERSION',   $data["minor"]);
                define('PHP_RELEASE_VERSION', $data["release"]);
            }
        }
    }

    /**
     * php版本对比
     */
    public static function phpVersionCompare($fromVersion,$toVersion,$operate="=")
    {
        $ok=version_compare($fromVersion, $toVersion, $operate);
        return $ok;
    }

    /**
     * 操作系统
     */
    public static function os()
    {
        $data=array();
        $data["isWin"]=strpos(strtoupper(PHP_OS), 'WIN') !== false ? true: false;
        $data["osName"]=$data["isWin"]?"Windows":"Linux";
        $data["osOrgName"]=PHP_OS;
        $data["sapi"]=PHP_SAPI;
        return $data;
    }

    /**
     * 服务器信息
     */
    public static function server()
    {
        $software=$_SERVER['SERVER_SOFTWARE'];
        if(strpos(strtolower($software),"apache")!==false){
            $software="Apache";
        }else if(strpos(strtolower($software),"nginx")!==false){
            $software="Nginx";
        }
        $data=array();
        $data["software"]=$software;
        return $data;
    }

    /**
     * linux 获取负载信息
     * @return array|null
     */
    public static function _getServerLoadLinuxData()
    {
        if (is_readable("/proc/stat"))
        {
            $stats = @file_get_contents("/proc/stat");

            if ($stats !== false)
            {
                // Remove double spaces to make it easier to extract values with explode()
                $stats = preg_replace("/[[:blank:]]+/", " ", $stats);

                // Separate lines
                $stats = str_replace(array("\r\n", "\n\r", "\r"), "\n", $stats);
                $stats = explode("\n", $stats);

                // Separate values and find line for main CPU load
                foreach ($stats as $statLine)
                {
                    $statLineData = explode(" ", trim($statLine));

                    // Found!
                    if
                    (
                        (count($statLineData) >= 5) &&
                        ($statLineData[0] == "cpu")
                    )
                    {
                        return array(
                            $statLineData[1],
                            $statLineData[2],
                            $statLineData[3],
                            $statLineData[4],
                        );
                    }
                }
            }
        }

        return null;
    }

    /**
     * 获取服务负载
     * @return int|null
     */
    public static function getServerLoad()
    {
        $load = null;
        if (stristr(PHP_OS, "win"))
        {
            $cmd = "wmic cpu get loadpercentage /all";
            @exec($cmd, $output);
            if ($output)
            {
                foreach ($output as $line)
                {
                    if ($line && preg_match("/^[0-9]+\$/", $line))
                    {
                        $load = $line;
                        break;
                    }
                }
            }
        }
        else
        {
            if (is_readable("/proc/stat"))
            {
                $statData1 = self::_getServerLoadLinuxData();
                sleep(1);
                $statData2 = self::_getServerLoadLinuxData();
                if((!is_null($statData1)) && (!is_null($statData2)))
                {
                    $statData2[0] -= $statData1[0];
                    $statData2[1] -= $statData1[1];
                    $statData2[2] -= $statData1[2];
                    $statData2[3] -= $statData1[3];
                    $cpuTime = $statData2[0] + $statData2[1] + $statData2[2] + $statData2[3];
                    $load = 100 - ($statData2[3] * 100 / $cpuTime);
                }
            }
        }
        return $load;
    }

    /**
     * 磁盘空间
     */
    public static function disk($directory)
    {
        $bytes = disk_free_space($directory);
        $bytesFormat=app("ltcmsFormat")::byte($bytes);

        $data=array();
        $data["bytes"]=$bytes;
        $data["bytesFormat"]=$bytesFormat;
        return $data;
    }

    /**
     * php配置信息
     */
    public static function phpIniData($key=null)
    {
        $iniPath = php_ini_loaded_file();
        $ini = @parse_ini_file($iniPath);
        if($key){
            if(isset($ini[$key])){
                $result=$ini[$key];
            }else{
                $result="";
            }
        }else{
            $result=$ini;
        }
        unset($ini);
        return $result;
    }

    /**
     * 获取php信息
     * @return array
     */
    public static function phpinfoArr($key=null)
    {
        ob_start();
        phpinfo();
        $info_arr = array();
        $info_lines = explode("\n", strip_tags(ob_get_clean(), "<tr><td><h2>"));
        $cat = "General";
        foreach($info_lines as $line)
        {
            preg_match("~<h2>(.*)</h2>~", $line, $title) ? $cat = $title[1] : null;
            if(preg_match("~<tr><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td></tr>~", $line, $val))
            {
                $info_arr[$cat][$val[1]] = $val[2];
            }
            elseif(preg_match("~<tr><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td></tr>~", $line, $val))
            {
                $info_arr[$cat][$val[1]] = array("local" => $val[2], "master" => $val[3]);
            }
        }
        if($key){
            return isset($info_arr[$key])?$info_arr[$key]:"";
        }else{
            return $info_arr;
        }
    }
}